package tw.edu.tku.im.maze.database;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import tw.edu.tku.im.maze.LoginRep;
import tw.edu.tku.im.maze.LoginReq;
import tw.edu.tku.im.maze.Packet;
import tw.edu.tku.im.maze.PlayerInfo;

public class LoginProcessor extends PacketProcessor {

   @Override
   String acceptName() {
      return "login";
   }

   @Override
   Packet process(Packet packet) {
      LoginReq req = (LoginReq)packet;
      try {
         Connection con = DriverManager.getConnection(address,user,passwd);
         con.setCatalog(database);
         CallableStatement cstmt = con.prepareCall("{call usp_loginCheck(?)}"); 
         cstmt.setString(1, req.getUserID().trim());
         cstmt.execute();
         ResultSet rs = cstmt.getResultSet();
         if(!rs.next()) {
//D               System.out.println("state=1");
            return new LoginRep(1);
         } 
         else {
            if(!req.getPassword().equals(rs.getString("password").trim())) {
//D               System.out.println("state=2");
               return new LoginRep(2);
            } 
            else {
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               String dateString = sdf.format(new Date());
               int[] parameter = new int[6];
               parameter[0] = rs.getInt("lv");
               parameter[1] = rs.getInt("exp");
               parameter[2] = rs.getInt("winsCount");
               parameter[3] = rs.getInt("lossesCount");
               parameter[4] = rs.getInt("leaverCount");
               parameter[5] = dateString.hashCode();
               PlayerInfo playerInfo = 
                     new PlayerInfo(req.getUserID().trim(), 
                                    rs.getString("username").trim(), parameter);
               cstmt = con.prepareCall("{call usp_loginUpdate(?, ?, ?)}");
               cstmt.setString(1, req.getUserID().trim());
               cstmt.setInt(2, parameter[5]);
               cstmt.setString(3, dateString);
               cstmt.execute();
               return new LoginRep(0, playerInfo);
            }
         }
      } catch (SQLException e) {
         e.printStackTrace();
      }        
      return new LoginRep(3);
   }

}
